<template>
	<div id="app">
		<PageSlide indexPagePath="/index">
			<router-view />
		</PageSlide>
		<BackToTop ref="backToTop" v-show="showBackToTop"></BackToTop>
		<tab v-if="!$route.meta.hideTabBar"></tab>

	</div>
</template>

<script>
	import PageSlide from '@/components/PageSlide'
	import BackToTop from '@/components/BackToTop'
	export default {
		data() {
			return {
				showBackToTop: false,


				socket: null,
				reconnectInterval: 2000, // 尝试重连的间隔，这里设置为2秒  
				attempts: 0, // 尝试重连的次数  
				maxAttempts: 5, // 最大尝试重连次数，超过后停止重连  


			};
		},
		mounted() {
			this.$nextTick(() => {
				window.addEventListener('scroll', this.handleScroll);
			});
		},
		created() {
			
			this.autoLogin();
			
			const pid = setInterval(()=>{
				if(this.$store.getters.getUser.uid != null && this.$store.getters.getUser.uid != ''){
					clearInterval(pid);
					this.connect();
				}
			},2000)
			
		},

		beforeDestroy() {
			this.closeConnection();
			window.removeEventListener('scroll', this.handleScroll);
		},
		watch: {
			'$route'(to, from) {
				// 路由变化时的逻辑处理  
				this.autoLogin();
			}
		},
		methods: {
			handleScroll() {
				this.showBackToTop = window.pageYOffset > 100; // 当滚动超过100px时显示  
			},

			autoLogin() {
				this.axios.get(`${this.IP}/getUserByToken`, {
					params: {
						token: this.getStorage('token'),
					}
				}).then(res => {
					if (res.data.result.includes('成功')) {
						let user = res.data.data;
						if (user.position == null) {
							this.$router.push('/firstLogin');
						}
						user.head_img = `${this.IP}` + user.head_img;
						this.$store.commit('setUser', user);
					} else {
						let new_user = {
							name: '未登录',
							head_img: `${this.IP}/img/未登录.png`,
							uid: '',
							score: null,
							position: null,
						}
						localStorage.removeItem('token');
						this.$store.commit('setUser', new_user);
					}
				})
			},
			
			
			connect() {
				let that = this;
				
			      const wsUrl = `wss://${this.WebSocketIP}/chat`;  
			      this.socket = new WebSocket(wsUrl);  
			  
			      this.socket.onopen = (event) => {
					  this.$store.commit('setSocket',this.socket);
			        console.log('WebSocket connection opened');  
			        this.attempts = 0; // 重置尝试次数  
			        // 这里可以发送一些初始化消息给后端  
					const initializationMessage = JSON.stringify({ action: 'initialize', data: {
						token: `${this.getStorage('token')}`
					} });
					this.socket.send(initializationMessage);  
			      };  
			  
			      this.socket.onmessage = (event) => {  
			        const message = event.data;
					console.log(message);
					if(message.includes('|')){
						let type = message.split('|')[0];
						if(type=="tip"){
							that.$toast.showMessage(message.split('|')[1]);
							setTimeout(function(){
								if(message.split('|')[1] == '您的订单状态已被对方操作,请刷新' && that.$route.path.includes('/orders')){
									location.reload();
								}
							},1500)
						}else if(type=="receive"){
							let obj={
								who_send:'',
								content:'',
								timestamp:0
							}
							obj.who_send = message.split("|")[1].split(",")[0];
							obj.content = message.split("|")[1].split(",")[1];
							obj.timestamp=new Date().getTime();
							let old_messages = that.$store.getters.getMessages;
							let already_has = false;
							old_messages.forEach((e)=>{
								if(e.uid.uid==obj.who_send){
									already_has=true;
									e.messages.push({
										content: obj.content,
										isRead: false,
										ender: "Contact",
										timestamp: obj.timestamp
									})
									e.unreadCount+=1;
									this.$store.commit('setMessages',old_messages);
									return true;
								}
							})
							

							if(already_has==false){
								this.axios.get(`${this.IP}/getUserByUID`, {
									params:{
										uid: obj.who_send
									}
								}).then(res => {
									let user = res.data;
									old_messages.push({
										latestTimestamp: obj.timestamp,
										messages:[
											{
												content: obj.content,
												isRead: false,
												ender: "Contact",
												timestamp: obj.timestamp
											}
										],
										uid: res.data,
										unreadCount: 1,
									})
									this.$store.commit('setMessages',old_messages);
								}).catch(error => {
									// 处理错误  
									console.error('请求出错：', error);
								});;
							}
							
							
							
							
							
							that.$toast.showMessage("您收到一条新消息");
						}
					}
					
			      };  
			  
			      this.socket.onerror = (error) => {  
			        console.error('WebSocket error:', error);  
			        this.reconnect(); // 在出现错误时尝试重连  
			      };  
			  
			      this.socket.onclose = (event) => {  
			        console.log('WebSocket connection closed');  
			        if (this.attempts < this.maxAttempts) {  
			          this.reconnect(); // 连接关闭时尝试重连  
			        } else {  
			          console.log('Max reconnect attempts reached. Stopping reconnect.');  
			        }  
			      };  
			    },  
			    reconnect() {
			      console.log(`Attempting to reconnect... (${this.attempts + 1}/${this.maxAttempts})`);  
			      setTimeout(() => {  
			        this.attempts++;  
			        this.connect();  
			      }, this.reconnectInterval);  
			    },  
			    closeConnection() {
			      if (this.socket) {  
			        this.socket.close();  
			        this.socket = null;  
			      }  
			    },  
			
			
			
		},
		components: {
			PageSlide,
			BackToTop
		}

	}
</script>



<style lang="less">
	.fade-enter-active,
	.fade-leave-active {
		transition: opacity 0.1s;
	}

	.fade-enter,
	.fade-leave-to {
		opacity: 0;
	}
</style>